package db

import (
	"errors"
	"log"
	"server_cluster/battle/sharemem"
	"strconv"
	"strings"
)

type Config_skill_card struct {
	Id        int32  `gorm:"primary_key;column:id;autoIncrement:false" csv:"Id"`
	Weight    int32  `gorm:"column:weight" csv:"Weight"`
	Target    int8   `gorm:"column:target" csv:"Cardtarget"`
	Tag       int8   `gorm:"column:tag" csv:"Tag"`
	Cold_time string `gorm:"column:cold_time" csv:"CardColdTime"`
	Skill1    string `gorm:"column:skill1" csv:"Skilllevel1"`
	Skill2    string `gorm:"column:skill2" csv:"Skilllevel2,omitempty"`
	Skill3    string `gorm:"column:skill3" csv:"Skilllevel3,omitempty"`
}

func (tmp *Config_skill_card) TableName() string {
	return "config_skill_card"
}

func (tmp *Config_skill_card) getAll() ([]*Config_skill_card, error) {
	var data []*Config_skill_card
	result := Conn.Find(&data)

	return data, result.Error
}

func (tmp *Config_skill_card) LoadData() error {
	data, err := tmp.getAll()
	if err != nil {
		return err
	}
	var myshm = &(sharemem.Myshm.Cfg.Sklcd)
	for key, value := range data {
		if key >= sharemem.MONSTER_MAX {
			return errors.New("config_skill_card format error 8")
		}
		myshm[key].Id = value.Id
		myshm[key].Weight = value.Weight
		myshm[key].Target = value.Target
		myshm[key].Tag = value.Tag
		cd := make([]int32, 3)
		if len(value.Cold_time) > 0 {
			c_list := strings.Split(value.Cold_time, ";")
			if len(c_list) > 3 {
				return errors.New("config_skill_card format error 1")
			}
			for k, v := range c_list {
				arg, err := strconv.Atoi(v)
				if err != nil {
					return errors.New("config_skill_card format error 11")
				}
				cd[k] = int32(arg)
			}
		}
		if len(value.Skill1) > 0 {
			b_list := strings.Split(value.Skill1, ";")
			if len(b_list) > sharemem.CARD_SKILL_MAX {
				return errors.New("config_skill_card format error 1")
			}
			myshm[key].Skill1.Cd_time = cd[0]
			for k, v := range b_list {
				arg, err := strconv.Atoi(v)
				if err != nil {
					return errors.New("config_skill_card format error 11")
				}
				myshm[key].Skill1.Ids[k] = int32(arg)
			}
		}
		if len(value.Skill2) > 0 {
			b_list := strings.Split(value.Skill2, ";")
			if len(b_list) > sharemem.CARD_SKILL_MAX {
				return errors.New("config_skill_card format error 2")
			}
			myshm[key].Skill2.Cd_time = cd[0]
			for k, v := range b_list {
				arg, err := strconv.Atoi(v)
				if err != nil {
					return errors.New("config_skill_card format error 22")
				}
				myshm[key].Skill2.Ids[k] = int32(arg)
			}
		}
		if len(value.Skill3) > 0 {
			b_list := strings.Split(value.Skill3, ";")
			if len(b_list) > sharemem.CARD_SKILL_MAX {
				return errors.New("config_skill_card format error 3")
			}
			myshm[key].Skill2.Cd_time = cd[0]
			for k, v := range b_list {
				arg, err := strconv.Atoi(v)
				if err != nil {
					return errors.New("config_skill_card format error 33")
				}
				myshm[key].Skill3.Ids[k] = int32(arg)
			}
		}
	}

	log.Println("load config_skill_card completed.")

	return nil
}
